package com.healthySys.backend.config.security.db;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.healthySys.backend.mapper.UserFullInfoVOMapper;
import com.healthySys.common.entity.UserFullInfoVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;

@Slf4j
@Configuration
public class DBUSerConfigManager implements UserDetailsManager, UserDetailsPasswordService {

    @Resource
    private UserFullInfoVOMapper userFullInfoVOMapper;

    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        return null;
    }

    @Override
    public void createUser(UserDetails user) {

    }

    @Override
    public void updateUser(UserDetails user) {

    }

    @Override
    public void deleteUser(String username) {

    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {

    }

    @Override
    public boolean userExists(String username) {
        return false;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<UserFullInfoVO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        UserFullInfoVO user = userFullInfoVOMapper.selectOne(queryWrapper);
        if(user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        return User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                //.authorities(AuthorityUtils.createAuthorityList(user.getAuthorities().split(","))) // 根据逗号分隔权限字符串生成权限列表 使用权限认证
                .roles(user.getRoleName())  // 添加角色信息 角色和权限不能直接混用 使用角色验证
                .accountExpired(false)
                .credentialsExpired(false)
                .accountLocked(false)
                .disabled(!user.getEnable())
                .build();
    }

}
